import 'package:animate_do/animate_do.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_openim_sdk/flutter_openim_sdk.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:openim_common/openim_common.dart';

double kInputBoxMinHeight = 56.h;

class ChatInputBox extends StatefulWidget {
  const ChatInputBox({
    Key? key,
    required this.toolbox,
    required this.voiceRecordBar,
    this.controller,
    this.focusNode,
    this.style,
    this.atStyle,
    this.enabled = true,
    this.isNotInGroup = false,
    this.hintText,
    this.forceCloseToolboxSub,
    this.quoteContent,
    this.quotedMessage, // 新增引用消息对象~
    this.onClearQuote,
    this.onSend,
    this.directionalText,
    this.onCloseDirectional,
    this.onTapVoice, // 新增语音按钮回调
  }) : super(key: key);
  final FocusNode? focusNode;
  final TextEditingController? controller;
  final TextStyle? style;
  final TextStyle? atStyle;
  final bool enabled;
  final bool isNotInGroup;
  final String? hintText;
  final Widget toolbox;
  final Widget voiceRecordBar;
  final Stream? forceCloseToolboxSub;
  final String? quoteContent;
  final Message? quotedMessage; // 新增引用消息对象
  final Function()? onClearQuote;
  final ValueChanged<String>? onSend;
  final TextSpan? directionalText;
  final VoidCallback? onCloseDirectional;
  final VoidCallback? onTapVoice; // 新增语音按钮回调

  @override
  State<ChatInputBox> createState() => _ChatInputBoxState();
}

class _ChatInputBoxState extends State<ChatInputBox> /*with TickerProviderStateMixin */ {
  bool _toolsVisible = false;
  bool _leftKeyboardButton = false;
  bool _sendButtonVisible = false;

  bool get _showQuoteView => IMUtils.isNotNullEmptyStr(widget.quoteContent);

  double get _opacity => (widget.enabled ? 1 : .4);

  bool get _showDirectionalView => widget.directionalText != null;

  @override
  void initState() {
    widget.focusNode?.addListener(() {
      if (widget.focusNode!.hasFocus) {
        setState(() {
          _toolsVisible = false;
          _leftKeyboardButton = false;
        });
      }
    });

    widget.forceCloseToolboxSub?.listen((value) {
      if (!mounted) return;
      setState(() {
        _toolsVisible = false;
      });
    });

    widget.controller?.addListener(() {
      setState(() {
        _sendButtonVisible = widget.controller!.text.isNotEmpty;
      });
    });

    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (!widget.enabled) widget.controller?.clear();
    return widget.isNotInGroup
        ? const ChatDisableInputBox()
        : Column(
            children: [
              Container(
                constraints: BoxConstraints(minHeight: kInputBoxMinHeight),
                color: Styles.c_F0F2F6,
                child: Row(
                  children: [
                    12.horizontalSpace,
                    // 新增语音按钮
                    GestureDetector(
                      onTap: _onTapVoice,
                      child: Container(
                        width: 32.w,
                        height: 32.h,
                        decoration: BoxDecoration(
                          color: Styles.c_FFFFFF,
                          borderRadius: BorderRadius.circular(16.r),
                        ),
                        child: Icon(
                          Icons.mic,
                          size: 20.w,
                          color: _leftKeyboardButton ? Styles.c_0089FF : Styles.c_8E9AB0,
                        ),
                      ),
                    ),
                    12.horizontalSpace,
                    Expanded(
                      child: Stack(
                        children: [
                          Offstage(
                            offstage: _leftKeyboardButton,
                            child: _textFiled,
                          ),
                          Offstage(
                            offstage: !_leftKeyboardButton,
                            child: widget.voiceRecordBar,
                          ),
                        ],
                      ),
                    ),
                    12.horizontalSpace,
                    (_sendButtonVisible ? ImageRes.sendMessage : ImageRes.openToolbox).toImage
                      ..width = 32.w
                      ..height = 32.h
                      ..opacity = _opacity
                      ..onTap = _sendButtonVisible ? send : toggleToolbox,
                    12.horizontalSpace,
                  ],
                ),
              ),
               // 引用消息显示区域
              if (_showQuoteView)
                _SubView(
                  title: null,
                  content: widget.quoteContent,
                  quotedMessage: widget.quotedMessage, // 传递引用消息对象
                  onClose: widget.onClearQuote,
                ),
              if (_showDirectionalView)
                _SubView(
                  textSpan: widget.directionalText,
                  onClose: () {
                    widget.onCloseDirectional?.call();
                  },
                ),
              Visibility(
                visible: _toolsVisible,
                child: FadeInUp(
                  duration: const Duration(milliseconds: 200),
                  child: widget.toolbox,
                ),
              ),
            ],
          );
  }

  void _onTapVoice() {
    if (!widget.enabled) return;
    setState(() {
      _leftKeyboardButton = !_leftKeyboardButton;
      _toolsVisible = false;
      if (_leftKeyboardButton) {
        unfocus();
      } else {
        focus();
      }
    });
    widget.onTapVoice?.call();
  }

  Widget get _textFiled => Container(
        margin: EdgeInsets.only(top: 10.h, bottom: _showQuoteView ? 4.h : 10.h),
        decoration: BoxDecoration(
          color: Styles.c_FFFFFF,
          borderRadius: BorderRadius.circular(4.r),
        ),
        child: ChatTextField(
          controller: widget.controller,
          focusNode: widget.focusNode,
          style: widget.style ?? Styles.ts_0C1C33_17sp,
          atStyle: widget.atStyle ?? Styles.ts_0089FF_17sp,
          enabled: widget.enabled,
          hintText: widget.hintText,
          textAlign: widget.enabled ? TextAlign.start : TextAlign.center,
        ),
      );

  void send() {
    if (!widget.enabled) return;
    if (null != widget.onSend && null != widget.controller) {
      widget.onSend!(widget.controller!.text.toString().trim());
    }
  }

  void toggleToolbox() {
    if (!widget.enabled) return;
    setState(() {
      _toolsVisible = !_toolsVisible;
      _leftKeyboardButton = false;
      if (_toolsVisible) {
        unfocus();
      } else {
        focus();
      }
    });
  }

  void onTapLeftKeyboard() {
    if (!widget.enabled) return;
    setState(() {
      _leftKeyboardButton = false;
      _toolsVisible = false;
      focus();
    });
  }

  void onTapRightKeyboard() {
    if (!widget.enabled) return;
    setState(() {
      _toolsVisible = false;
      focus();
    });
  }

  focus() => FocusScope.of(context).requestFocus(widget.focusNode);

  unfocus() => FocusScope.of(context).requestFocus(FocusNode());
}

class _SubView extends StatelessWidget {
  const _SubView({
    this.onClose,
    this.title,
    this.content,
    this.textSpan,
    this.quotedMessage, // 新增引用消息对象
  }) : assert(content != null || textSpan != null, 'Either content or textSpan must be provided.');
  final VoidCallback? onClose;
  final String? title;
  final String? content;
  final InlineSpan? textSpan;
  final Message? quotedMessage; // 新增引用消息对象

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(bottom: 10.h, left: 56.w, right: 56.w), 
      color: Styles.c_F0F2F6,
      child: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: onClose,
        child: Container(
          padding: EdgeInsets.symmetric(vertical: 8.h, horizontal: 12.w),
          decoration: BoxDecoration(
            color: Styles.c_FFFFFF,
            borderRadius: BorderRadius.circular(4.r),
            // border: Border(
            //   left: BorderSide(
            //     color: Styles.c_0089FF,
            //     width: 3.w,
            //   ),
            // ),
          ),
            child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              // 缩略图区域 - 独立的点击区域
              if (_shouldShowThumbnail())
                Container(
                  margin: EdgeInsets.only(right: 8.w),
                  child: _buildThumbnail(),
                ),
              // 文本内容区域 - 点击关闭引用
              Expanded(
                child: GestureDetector(
                  onTap: onClose,
                  behavior: HitTestBehavior.translucent,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      if (title != null)
                        Text(
                          title!,
                          style: Styles.ts_0089FF_12sp,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      if (content != null)
                        Text(
                          content!,
                          style: Styles.ts_8E9AB0_14sp,
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                        ),
                      if (textSpan != null)
                        RichText(
                          text: textSpan!,
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                        ),
                    ],
                  ),
                ),
              ),
              8.horizontalSpace,
              // 关闭按钮
              GestureDetector(
                onTap: onClose,
                child: ImageRes.delQuote.toImage
                  ..width = 14.w
                  ..height = 14.h,
              ),
            ],
          ),
             
          
        ),
      ),
    );
  }
   // 判断是否应该显示缩略图
  bool _shouldShowThumbnail() {
    if (quotedMessage == null) return false;
    final contentType = quotedMessage!.contentType;
    return contentType == MessageType.picture || contentType == MessageType.video;
  }

   // 构建缩略图
  Widget _buildThumbnail() {
    if (quotedMessage == null) return const SizedBox.shrink();

    final contentType = quotedMessage!.contentType;
    
    return GestureDetector(
      onTap: () => _openQuotedMedia(),
      child: contentType == MessageType.picture 
          ? _buildPictureThumbnail()
          : contentType == MessageType.video
              ? _buildVideoThumbnail()
              : const SizedBox.shrink(),
    );
  }
   // 打开引用的媒体内容
  void _openQuotedMedia() {
    if (quotedMessage == null) return;
    
    final contentType = quotedMessage!.contentType;
    
    if (contentType == MessageType.picture) {
      // 打开图片预览
      IMUtils.previewPicture(quotedMessage!);
    } else if (contentType == MessageType.video) {
      // 打开视频播放
      IMUtils.previewMediaFile(
        context: Get.context!,
        message: quotedMessage!,
      );
    }
  }

  // 构建图片缩略图
  Widget _buildPictureThumbnail() {
    final pictureElem = quotedMessage!.pictureElem;
    final thumbnailUrl = pictureElem?.sourcePicture?.url;
    
    return Container(
      width: 32.w,
      height: 32.w,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(4.r),
        color: Styles.c_F0F2F6,
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(4.r),
        child: thumbnailUrl?.isNotEmpty == true
            ? Image.network(
                thumbnailUrl!,
                width: 32.w,
                height: 32.w,
                fit: BoxFit.cover,
                errorBuilder: (context, error, stackTrace) {
                  return Icon(
                    Icons.image,
                    size: 16.w,
                    color: Styles.c_8E9AB0,
                  );
                },
              )
            : Icon(
                Icons.image,
                size: 16.w,
                color: Styles.c_8E9AB0,
              ),
      ),
    );
  }

  // 构建视频缩略图
  Widget _buildVideoThumbnail() {
    final videoElem = quotedMessage!.videoElem;
    final thumbnailUrl = videoElem?.snapshotUrl;
    
    return Container(
      width: 32.w,
      height: 32.w,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(4.r),
        color: Styles.c_F0F2F6,
      ),
      child: Stack(
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(4.r),
            child: thumbnailUrl?.isNotEmpty == true
                ? Image.network(
                    thumbnailUrl!,
                    width: 32.w,
                    height: 32.w,
                    fit: BoxFit.cover,
                    errorBuilder: (context, error, stackTrace) {
                      return Icon(
                        Icons.videocam,
                        size: 16.w,
                        color: Styles.c_8E9AB0,
                      );
                    },
                  )
                : Icon(
                    Icons.videocam,
                    size: 16.w,
                    color: Styles.c_8E9AB0,
                  ),
          ),
          // 播放按钮覆盖层
          Positioned.fill(
            child: Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(4.r),
                color: Colors.black.withOpacity(0.3),
              ),
              child: Icon(
                Icons.play_arrow,
                color: Colors.white,
                size: 12.w,
              ),
            ),
          ),
        ],
      ),
    );
  }
}
